<?php
/**
 * 系统安装脚本
 * 创建必要的目录和检查环境配置
 */

// 安全检查：安装完成后应删除此文件
$installLockFile = __DIR__ . '/.installed';
if (file_exists($installLockFile)) {
    die('❌ 系统已经安装过了！如需重新安装，请先删除 .installed 文件');
}

$errors = [];
$warnings = [];
$success = [];
$directories = ['logs', 'temp'];

// 检查PHP版本
$phpVersion = phpversion();
if (version_compare($phpVersion, '7.0.0', '<')) {
    $errors[] = "PHP版本过低，当前版本: {$phpVersion}，需要 >= 7.0.0";
} else {
    $success[] = "PHP版本检查通过: {$phpVersion}";
}

// 检查必需的PHP扩展
$requiredExtensions = ['pdo', 'pdo_mysql', 'json', 'mbstring'];
foreach ($requiredExtensions as $ext) {
    if (!extension_loaded($ext)) {
        $errors[] = "缺少必需的PHP扩展: {$ext}";
    } else {
        $success[] = "PHP扩展 {$ext} 已加载";
    }
}

// 检查配置文件
if (!file_exists(__DIR__ . '/config/config.php')) {
    $warnings[] = "配置文件 config/config.php 不存在，请从 config.example.php 复制";
}

if (!file_exists(__DIR__ . '/config/database.php')) {
    $warnings[] = "数据库配置文件 config/database.php 不存在";
}

// 创建必要的目录
foreach ($directories as $dir) {
    $dirPath = __DIR__ . '/' . $dir;
    
    if (file_exists($dirPath)) {
        if (is_dir($dirPath)) {
            if (is_writable($dirPath)) {
                $success[] = "目录 {$dir}/ 已存在且可写";
            } else {
                $errors[] = "目录 {$dir}/ 存在但不可写，请检查权限";
            }
        } else {
            $errors[] = "{$dir} 存在但不是目录，请删除后重新安装";
        }
    } else {
        // 尝试创建目录
        if (@mkdir($dirPath, 0755, true)) {
            $success[] = "成功创建目录: {$dir}/";
            
            // 创建 .gitkeep 文件
            file_put_contents($dirPath . '/.gitkeep', '');
            
            // 为 logs 目录创建 README
            if ($dir === 'logs') {
                file_put_contents($dirPath . '/README.md', "# 日志目录\n\n此目录用于存储应用程序日志文件。\n\n日志文件命名格式：`app_YYYY-MM-DD.log`\n");
            }
            
            // 为 temp 目录创建 README
            if ($dir === 'temp') {
                file_put_contents($dirPath . '/README.md', "# 临时文件目录\n\n此目录用于存储搜索结果的临时HTML文件。\n\n文件会定期清理，建议每周运行一次 `php cleanup_temp.php`。\n");
            }
        } else {
            $errors[] = "无法创建目录 {$dir}/，请检查权限";
        }
    }
}

// 检查 .gitignore
$gitignorePath = __DIR__ . '/.gitignore';
if (file_exists($gitignorePath)) {
    $gitignoreContent = file_get_contents($gitignorePath);
    $needsUpdate = false;
    $gitignoreEntries = [];
    
    if (strpos($gitignoreContent, 'logs/') === false) {
        $gitignoreEntries[] = 'logs/';
        $needsUpdate = true;
    }
    
    if (strpos($gitignoreContent, 'temp/') === false) {
        $gitignoreEntries[] = 'temp/';
        $needsUpdate = true;
    }
    
    if ($needsUpdate) {
        file_put_contents($gitignorePath, "\n" . implode("\n", $gitignoreEntries) . "\n", FILE_APPEND);
        $success[] = "已更新 .gitignore 文件";
    }
} else {
    $warnings[] = ".gitignore 文件不存在";
}

// 测试数据库连接
try {
    if (file_exists(__DIR__ . '/config/database.php')) {
        require_once __DIR__ . '/config/database.php';
        require_once __DIR__ . '/classes/Database.php';
        
        $db = Database::getInstance();
        $connection = $db->getConnection();
        
        if ($connection) {
            $success[] = "数据库连接测试成功";
            
            // 检查 keyword 表是否存在
            $stmt = $connection->query("SHOW TABLES LIKE 'keyword'");
            if ($stmt->rowCount() > 0) {
                $success[] = "数据库表 keyword 已存在";
                
                // 检查表结构
                $stmt = $connection->query("DESCRIBE keyword");
                $columns = $stmt->fetchAll(PDO::FETCH_COLUMN);
                
                $requiredColumns = ['id', 'type', 'keyword', 'add_time', 'update_time', 'is_read'];
                $missingColumns = array_diff($requiredColumns, $columns);
                
                if (empty($missingColumns)) {
                    $success[] = "数据库表结构检查通过";
                } else {
                    $warnings[] = "数据库表缺少字段: " . implode(', ', $missingColumns);
                }
            } else {
                $warnings[] = "数据库表 keyword 不存在，请手动创建";
            }
        }
    }
} catch (Exception $e) {
    $warnings[] = "数据库连接测试失败: " . $e->getMessage();
}

// 检查文件权限
$filesToCheck = [
    'config/config.php' => false, // 不需要可写
    'classes/' => false,
    'api/' => false,
];

foreach ($filesToCheck as $file => $needsWritable) {
    $filePath = __DIR__ . '/' . $file;
    if (file_exists($filePath)) {
        if ($needsWritable && !is_writable($filePath)) {
            $warnings[] = "{$file} 不可写";
        }
    }
}

// 如果没有致命错误，创建安装锁定文件
$canInstall = empty($errors);
if ($canInstall && isset($_POST['confirm_install'])) {
    file_put_contents($installLockFile, date('Y-m-d H:i:s'));
    $installComplete = true;
} else {
    $installComplete = false;
}

?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>系统安装 - 神马搜索关键词轮播系统</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        
        .container {
            max-width: 800px;
            margin: 0 auto;
            background: white;
            border-radius: 12px;
            box-shadow: 0 10px 40px rgba(0,0,0,0.2);
            overflow: hidden;
        }
        
        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }
        
        .header h1 {
            font-size: 28px;
            margin-bottom: 10px;
        }
        
        .header p {
            opacity: 0.9;
            font-size: 14px;
        }
        
        .content {
            padding: 30px;
        }
        
        .section {
            margin-bottom: 30px;
        }
        
        .section h2 {
            color: #333;
            font-size: 20px;
            margin-bottom: 15px;
            padding-bottom: 10px;
            border-bottom: 2px solid #f0f0f0;
        }
        
        .check-item {
            padding: 12px;
            margin-bottom: 8px;
            border-radius: 6px;
            display: flex;
            align-items: center;
        }
        
        .check-item.success {
            background: #d4edda;
            color: #155724;
        }
        
        .check-item.warning {
            background: #fff3cd;
            color: #856404;
        }
        
        .check-item.error {
            background: #f8d7da;
            color: #721c24;
        }
        
        .check-item .icon {
            margin-right: 10px;
            font-size: 18px;
        }
        
        .check-item .message {
            flex: 1;
            font-size: 14px;
        }
        
        .summary {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 20px;
        }
        
        .summary-item {
            display: flex;
            justify-content: space-between;
            padding: 8px 0;
            border-bottom: 1px solid #e9ecef;
        }
        
        .summary-item:last-child {
            border-bottom: none;
        }
        
        .summary-label {
            color: #666;
            font-weight: 500;
        }
        
        .summary-value {
            font-weight: 600;
        }
        
        .summary-value.success {
            color: #28a745;
        }
        
        .summary-value.warning {
            color: #ffc107;
        }
        
        .summary-value.error {
            color: #dc3545;
        }
        
        .btn {
            width: 100%;
            padding: 14px;
            border: none;
            border-radius: 8px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
        }
        
        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }
        
        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 20px rgba(102, 126, 234, 0.4);
        }
        
        .btn-success {
            background: #28a745;
            color: white;
        }
        
        .btn:disabled {
            opacity: 0.5;
            cursor: not-allowed;
            transform: none;
        }
        
        .alert {
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
        }
        
        .alert-success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        
        .alert-error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        
        .next-steps {
            background: #e7f3ff;
            border-left: 4px solid #2196F3;
            padding: 15px;
            border-radius: 4px;
            margin-top: 20px;
        }
        
        .next-steps h3 {
            color: #1976D2;
            margin-bottom: 10px;
            font-size: 16px;
        }
        
        .next-steps ol {
            margin-left: 20px;
            color: #555;
        }
        
        .next-steps li {
            margin: 5px 0;
            font-size: 14px;
        }
        
        .code-block {
            background: #f5f5f5;
            border: 1px solid #ddd;
            border-radius: 4px;
            padding: 10px;
            margin: 10px 0;
            font-family: 'Courier New', monospace;
            font-size: 13px;
            overflow-x: auto;
        }
        
        .footer {
            text-align: center;
            padding: 20px;
            color: #666;
            font-size: 12px;
            border-top: 1px solid #f0f0f0;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🚀 系统安装向导</h1>
            <p>检查系统环境并创建必要的目录</p>
        </div>
        
        <div class="content">
            <?php if ($installComplete): ?>
                <div class="alert alert-success">
                    <h3 style="margin-bottom: 10px;">✅ 安装完成！</h3>
                    <p>系统已成功安装，您现在可以开始使用了。</p>
                </div>
                
                <div class="next-steps">
                    <h3>📝 下一步操作：</h3>
                    <ol>
                        <li>删除安装文件（安全建议）：
                            <div class="code-block">rm install.php</div>
                        </li>
                        <li>访问主页面：
                            <div class="code-block">index.php</div>
                        </li>
                        <li>导入关键词：
                            <div class="code-block">import_keywords.php</div>
                        </li>
                        <li>查看日志：
                            <div class="code-block">view_log.php</div>
                        </li>
                    </ol>
                </div>
                
                <div style="margin-top: 20px;">
                    <a href="index.php" style="text-decoration: none;">
                        <button class="btn btn-success">进入系统</button>
                    </a>
                </div>
                
            <?php else: ?>
                <div class="summary">
                    <h2 style="margin-bottom: 15px;">安装检查摘要</h2>
                    <div class="summary-item">
                        <span class="summary-label">✅ 通过项</span>
                        <span class="summary-value success"><?php echo count($success); ?></span>
                    </div>
                    <div class="summary-item">
                        <span class="summary-label">⚠️ 警告项</span>
                        <span class="summary-value warning"><?php echo count($warnings); ?></span>
                    </div>
                    <div class="summary-item">
                        <span class="summary-label">❌ 错误项</span>
                        <span class="summary-value error"><?php echo count($errors); ?></span>
                    </div>
                </div>
                
                <?php if (!empty($success)): ?>
                    <div class="section">
                        <h2>✅ 检查通过 (<?php echo count($success); ?>)</h2>
                        <?php foreach ($success as $item): ?>
                            <div class="check-item success">
                                <span class="icon">✓</span>
                                <span class="message"><?php echo htmlspecialchars($item); ?></span>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
                
                <?php if (!empty($warnings)): ?>
                    <div class="section">
                        <h2>⚠️ 警告 (<?php echo count($warnings); ?>)</h2>
                        <?php foreach ($warnings as $item): ?>
                            <div class="check-item warning">
                                <span class="icon">⚠</span>
                                <span class="message"><?php echo htmlspecialchars($item); ?></span>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
                
                <?php if (!empty($errors)): ?>
                    <div class="section">
                        <h2>❌ 错误 (<?php echo count($errors); ?>)</h2>
                        <?php foreach ($errors as $item): ?>
                            <div class="check-item error">
                                <span class="icon">✗</span>
                                <span class="message"><?php echo htmlspecialchars($item); ?></span>
                            </div>
                        <?php endforeach; ?>
                    </div>
                    
                    <div class="alert alert-error">
                        <strong>无法继续安装</strong><br>
                        请先解决上述错误后再重新运行安装程序。
                    </div>
                <?php endif; ?>
                
                <?php if (empty($errors)): ?>
                    <form method="POST">
                        <button type="submit" name="confirm_install" class="btn btn-primary">
                            确认安装
                        </button>
                    </form>
                    
                    <?php if (!empty($warnings)): ?>
                        <div class="next-steps" style="margin-top: 20px; background: #fff3cd; border-left-color: #ffc107;">
                            <h3 style="color: #856404;">⚠️ 注意事项：</h3>
                            <p style="color: #856404; font-size: 14px; margin-top: 10px;">
                                虽然存在警告项，但您仍然可以继续安装。建议在使用前解决这些警告。
                            </p>
                        </div>
                    <?php endif; ?>
                <?php endif; ?>
            <?php endif; ?>
        </div>
        
        <div class="footer">
            神马搜索关键词轮播系统 v1.0 | 2025
        </div>
    </div>
</body>
</html>
